/*
	checksum.
	Copyright (C) 2012 pioneer suntec
	2012/08/03	leichang
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

unsigned char const version_info[] = "Ver1.0.0";

static void usage(void);

void usage(void)
{
	fprintf (stderr, 
			 "usage:\n"
			 "checksum.exe -i inputfile -o outputfile\n"
			 "\t-i inputfile    : Set input file name.\n"
			 "\t-o outputfile   : Set output file name.\n"
			 "\t-V              : Display version information.\n");
	exit(1);
}

int main (int argc, char *argv[])
{
	int i;
	FILE* filein = NULL;
	FILE* fileout = NULL;
	unsigned char ucData;
	unsigned long checksum;
	unsigned char* pInputFile = NULL;
	unsigned char* pOutputFile = NULL;

	if( 1 == argc )
	{
		usage();
	}

	/* Analyze parameters */
	for( i=1; i<argc; i++ )
	{
		if( '-' == argv[i][0] )
		{
			switch( argv[i][1] )
			{
				case 'i':
					if( argv[i][2] != '\0' )
					{
						usage();
					}
					else
					{
						pInputFile = argv[++i];
					}
					break;

				case 'o':
					if( argv[i][2] != '\0' )
					{
						usage();
					}
					else
					{
						pOutputFile = argv[++i];
					}
					break;

				case 'V':
					if( argv[i][2] != '\0' )
					{
						usage();
					}
					else
					{
						fprintf (stdout, "checksum %s, Copyright (C) 2012 Pioneer Suntec.\n", version_info);
					}
					break;

				default:
					usage();    
					break;
			}
		}
		else
		{
			usage();
		}
	}

	if( NULL == pInputFile )
	{
		usage();
	}
	
	if( NULL == pOutputFile )
	{
		usage();
	}

	filein = fopen(pInputFile, "rb");
	if( NULL == filein )
	{
		fprintf(stderr, "Can't open file \'%s\'.\n", pInputFile);
		exit(1);
	}

	fileout = fopen(pOutputFile, "w");
	if( NULL == fileout )
	{
		fprintf(stderr, "Can't open file \'%s\'.\n", pOutputFile);
		exit(1);
	}

	checksum = 0x00000000;
	fscanf(filein, "%c", &ucData);
	while( !feof(filein) )
	{
		checksum += ucData & 0x000000FF;
		fscanf(filein, "%c", &ucData);
	}

	fprintf(fileout, "%04X", checksum);

	fclose(filein);
	filein = NULL;
	fclose(fileout);
	fileout = NULL;

	return 0;
}








